import type { Router } from 'vue-router'
import NProgress from 'nprogress'
import qs from 'qs'
import 'nprogress/nprogress.css'

import { useTheme } from '@/store/modules/theme'
import { useUser } from '@/store/modules/user'
import { useHttp } from '@/store/modules/http'
import { load } from '@/plugins/loading'

import config from '@/config'
import { getStorage } from '@/utils/storage'

let getInfoFlag = false

// 路由拦截
export function setupPermission(router: Router) {
  router.beforeEach(async (to, from) => {
    console.log('path', to.path, from.path)

    if (to.path === from.path) return true
    // 清除之前页面的请求 因为/会被重定向至/home，导致在/请求的初始数据接口会被拦截掉，所以加个过滤
    if (!['/'].includes(from.path)) {
      const http = useHttp()
      http.clearToken()
    }

    const theme = useTheme()
    NProgress.configure({
      template: `<div class="bar" style="background: ${theme.primary}"  role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>`
    })
    NProgress.start()
    // if (!config.needLogin) return true
    const user = useUser()
    const {
      userInfo,
      userMenu,
      oauth: { token },
      getUserInfo,
      loginOutNetWork,
      getUserMenu,
      getUserDict
      // iamLogin
    } = user
    // await ssoLogin(to.href, iamLogin)
    const storageToken = getStorage('token') ?? ''
    console.log(
      '!userInfo.id || userMenu.length < 1',
      !userInfo.id,
      userMenu.length < 1
    )
    if (to.path !== '/login') {
      if (!(token && storageToken)) return '/login'
      if (!userInfo.id || userMenu.length < 1) {
        load.show()
        getInfoFlag = true
        // const res = await Promise.all([
        //   // 个人信息
        //   getUserInfo(),
        //   // 菜单
        //   getUserMenu(),
        //   // 字段
        //   getUserDict()
        // ])
        // 个人信息
        const flagInfo = await getUserInfo()
        let flagMenu
        if (flagInfo) {
          // 菜单
          flagMenu = await getUserMenu()
        }
        // @Todo:字典
        // const dictFlag = await getUserDict()

        // const [flagInfo, flagMenu, dictFlag] = res
        // 放开路由
        if (
          flagInfo &&
          flagMenu
          // && dictFlag
        ) {
          return { ...to, replace: true }
        } else {
          // 退出等咯
          await loginOutNetWork()
          window['$message'].error('获取基础数据失败')
        }
      } else {
        return true
      }
    } else {
      // 登录页重定向到首页
      if (token && storageToken) return '/home'
    }
  })
  router.afterEach(() => {
    if (getInfoFlag) load.hide(), (getInfoFlag = false)
    NProgress.done()
  })
}
//单点登录
// async function ssoLogin(href, login) {
//   const regValid = RegExp(/^(?=.*applicationId)(?=.*cert)/g)
//   const regQuery = RegExp(/(\?applicationId.*)/g)
//   if (regValid.test(href)) {
//     const matchHref = href.match(regQuery)
//     if (Array.isArray(matchHref) && matchHref.length > 0) {
//       const query = qs.parse(matchHref[0], { ignoreQueryPrefix: true })
//       await login(query)
//     }
//   }
// }
